
define(['ionic', 'controllers'], function () {
    angular.module('U9Mobile.controllers')
        .controller('ChatCtrl', ['$scope', '$ionicHistory', '$ionicPlatform', '$timeout', '$ionicModal', '$ionicScrollDelegate', '$cordovaContacts', 'ContactService', 'UtilService', 'AppConstants',
            function ($scope, $ionicHistory, $ionicPlatform, $timeout, $ionicModal, $ionicScrollDelegate, $cordovaContacts, ContactService, UtilService, AppConstants) {
                $scope.data = {
                    manualAdd: null,
                    delete: false,
                    participators: [],
                    pickSource: true, // true: 企业联系人 false: 手机通讯录
                    search: '',
                    tips: '',
                    contacts: [],
                    location: false
                };

                $scope.$on('$ionicView.afterEnter', function () {
                    $timeout(init);
                });

                $ionicModal.fromTemplateUrl('tpls/dudu/pickContacts.html', {
                    scope: $scope,
                    animation: 'slide-in-right'
                }).then(function(modal) {
                    $scope.modal = modal;
                });
                var _deregisterBackButton;
                $scope.$on('$destroy', function () {
                    $scope.modal.remove();
                    if (_deregisterBackButton) {
                        _deregisterBackButton();
                    }
                });

                $scope.manualAdd = function () {
                    maybeTipsAddible();
                    var temp = $scope.data.manualAdd.toString();
                    addContact({
                        name: '...' + temp.substr(temp.length - 4),
                        phone: $scope.data.manualAdd
                    });
                    $scope.data.manualAdd = '';
                };
                $scope.onHoldImg = function () {
                    $scope.data.delete = !$scope.data.delete;
                    if ($scope.data.delete) {
                        _deregisterBackButton = $ionicPlatform.registerBackButtonAction(function () {
                                $scope.$apply($scope.onHoldImg);
                            },
                            AppConstants.PLATFORM_BACK_BUTTON_VIEW_FN
                        );
                    } else {
                        if (_deregisterBackButton) {
                            _deregisterBackButton();
                        }
                    }
                };
                $scope.manualDelete = function (index) {
                    $scope.data.participators.splice(index, 1);
                    if ($scope.data.participators.length === 0) {
                        $scope.onHoldImg();
                    }
                };
                $scope.createConference = function () {
                    if ($scope.data.participators.length === 0) {
                        UtilService.tipsCenter('请添加参与人');
                        return;
                    }
                    UtilService.showLoading();
                    ContactService.createConference(collectPhones()).then(function () {
                        UtilService.alert('发起通话成功，点击确认返回').then(function () {
                            $ionicHistory.goBack();
                        });
                        UtilService.hideLoading();
                    }, function (error) {
                        UtilService.tipsCenter(error);
                        UtilService.hideLoading();
                    });
                };
                $scope.goBack = function () {
                    $ionicHistory.goBack();
                };

                $scope.pickCorporateContact = function () {
                    $scope.data.pickSource = true;
                    $scope.data.search = '';
                    $scope.modal.show().then(function () {
                        initContacts();
                    });
                };
                $scope.pickPhoneContact = function () {
                    $scope.data.pickSource = false;
                    $scope.data.search = '';
                    $scope.modal.show().then(function () {
                        initContacts();
                    });
                };

                $scope.setChar = function (char) {
                    if (char === '*') {
                        $scope.data.location = false;
                        if ($scope.data.search !== '') {
                            $scope.data.search = '';
                        } else {
                            initContacts();
                        }
                    } else {
                        $scope.data.tips = char;
                        $scope.data.contacts = ContactService.getContacts(char, $scope.data.pickSource);
                        $scope.data.location = true;
                    }
                };
                var afterViewEnter = false;
                $scope.$on('$ionicView.afterEnter', function () {
                    afterViewEnter = true;
                });
                $scope.$watch('data.search', function (search) {
                    if (!afterViewEnter) {
                        return;
                    }
                    if (search === '' || search === '1') {
                        initContacts();
                        $scope.data.location = false;
                    } else {
                        ContactService.filterContacts(search, $scope.data.pickSource).then(function (contacts) {
                            if (contacts.length === 0) {
                                $scope.data.tips = '没有找到符合条件联系人';
                            } else {
                                $scope.data.tips = '共找到' + contacts.length + '个联系人';
                            }
                            $scope.data.contacts = contacts;
                        });
                    }
                });

                $scope.submit = function () {
                    progressPickContact();
                    $scope.modal.hide();
                };
                $scope.cancel = function () {
                    $scope.modal.hide();
                };
                $scope.$on('modal.hidden', function() {
                    $scope.data.contacts = [];
                    $scope.data.location = false;
                    $scope.data.search = '';
                });

                function progressPickContact () {
                    var hasContact = false;
                    angular.forEach($scope.data.contacts, function (contact) {
                        if (contact.checked) {
                            if (!hasContact) {
                                hasContact = true;
                            }
                            var temp = contact.name,
                                reg=/^[\u4e00-\u9fa5]+$/,
                                maxChar = 5;
                            if (reg.test(temp)) {
                                maxChar *= 2;
                            }
                            if (temp.length > maxChar) {
                                contact.name = '...' + temp.substr(temp.length - maxChar);
                            }
                            addContact(contact);
                        }
                    });
                    if (hasContact) {
                        maybeTipsAddible();
                    }
                }
                function init () {
                    UtilService.showLoading();
                    ContactService.getInitParticipators().then(function (participators) {
                        $scope.data.participators = participators;
                    }).finally(function () {
                        UtilService.hideLoading();
                    });
                }
                function initContacts () {
                    ContactService.queryContacts($scope.data.pickSource).then(function (results) {
                        $scope.data.contacts = results;
                        $scope.data.tips = '';
                    });
                }
                function collectPhones () {
                    var phones = '';
                    angular.forEach($scope.data.participators, function (participator) {
                        phones += ',';
                        phones += participator.phone;
                    });
                    return phones.substr(1);
                }
                function maybeTipsAddible() {
                    if ($scope.data.participators.length === AppConstants.MAX_CALLER_NUM) {
                        UtilService.tipsCenter('最多添加8个参与人');
                    }
                }
                function addContact (contact) {
                    if (checkAddible(contact.phone)) {
                        $scope.data.participators.push(contact);
                    }
                }
                function checkAddible (phone) {
                    var participators = $scope.data.participators,
                        len = participators.length;
                    if (len === 8) {
                        return false;
                    }
                    for (var i = 0; i < len; i++) {
                        if (participators[i].phone === phone) {
                            return false;
                        }
                    }
                    return true;
                }
            }
        ]);
});